package com.lib.image.preview

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.Navigation
import com.lib.image.ImageLoader
import com.lib.image.R
import com.lib.image.databinding.FragmentCoverClipBinding
import com.lib.image.ex.showToast
import com.lib.image.until.FileUtil
import com.zhihu.matisse.ui.MatisseActivity
import java.lang.Exception

class CoverClipFragment: Fragment() {

    private val mPath by lazy { CoverClipFragmentArgs.fromBundle(requireArguments()).path }
    private val mIndex by lazy { CoverClipFragmentArgs.fromBundle(requireArguments()).index }

    private lateinit var mViewBinding: FragmentCoverClipBinding

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mViewBinding = FragmentCoverClipBinding.inflate(inflater, container, false)
        return mViewBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mViewBinding.run {
            rectLayout.setFixed(true, 400)
            btnBack.setOnClickListener {
                Navigation.findNavController(view).navigateUp()
            }
            btnSave.setOnClickListener {
                if(null == rectLayout.bitmap) {
                    showToast("数据加载中...")
                    return@setOnClickListener
                }
                try {
                    val bitmap = rectLayout.clip()
                    val file = FileUtil.createImageFile(requireContext(), "clip_${System.currentTimeMillis()}.jpg}")
                    FileUtil.saveBitmap(requireContext(), bitmap, file, 100)
                    val intent = Intent()
                    val list = arrayListOf<String>()
                    list.add(file.absolutePath)
                    intent.putExtra(MatisseActivity.EXTRA_RESULT_SELECTION_PATH, list)
                    intent.putExtra(MatisseActivity.EXTRA_RESULT_INDEX, mIndex)
                    activity?.setResult(Activity.RESULT_OK, intent)
                    activity?.finish()
                } catch (e: Exception){
                    showToast(e.message?:"数据异常")
                }
            }
        }
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        mViewBinding.rectLayout.run {
            ImageLoader.loadFitCenterImage(imageView, mPath, measuredWidth, height, fragment = this@CoverClipFragment)
        }
    }
}